package com.example.demo.controller;

import com.example.demo.dto.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@RequestMapping("/cache")
public class CacheController {

    @Autowired
    private CacheManager cacheManager;

//    @Autowired
//    @Qualifier(value="redisCacheManager")
//    private CacheManager redisCacheManager;

    @GetMapping("/get")
//    @Cacheable(key="#person.name")
    @Cacheable(value="models",key="#person.name")
    public Person getPerson(Person person){
        System.out.println("Person.address:"+person.getAddress());
        return person;
    }

    //    无条件全部cache,不带key，默认是空？
    @PostMapping("/get/new")
    @Cacheable(value="new")
    public Person getNewCache(Person Person){
        Person.setName(Person.getName().toUpperCase());
        return Person;
    }

    //删除cache
    @DeleteMapping("/delete/{name}")
    @CacheEvict(value="models",key="#name")
    public String deleteCache(@PathVariable("name") String name){
        System.out.println("system input name:"+name);
        return "delete Cache success!";
    }

    @PutMapping("/put")
    @CachePut(value="models",key="#person.name")
    public Person putCache(Person person){
        System.out.println("key:"+person.getName()+","+"address:"+person.getAddress());
        return person;
    }

    @GetMapping("/get/all")
    public List<Person> getAll(){
//        Map map=new HashMap<String,Person>();
        List list=new ArrayList();
//        这个里面没有流
//        cacheManager.getCacheNames().stream().forEach(s-> {list.add(s);System.out.println(s);});
        Map<String, Object> map2=(Map<String, Object>)cacheManager.getCache("models").getNativeCache();
        map2.forEach((k,v)-> System.out.println(k.toString()+":"+v.toString()));
//        System.out.println("cache:"+cacheManager.getCache("models").getNativeCache());
        return list;
//        Cache cache=cacheManager.getCache("models");
//        Object o=cacheManager.getCache("models").getNativeCache();
//        System.out.println("cacheName:"+);
//        获取cache模型
//        Object cache=cacheManager.getCache("models").getNativeCache();
    }
}